package com.zhengbaochuan.web.action.util;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class BaseAction<T> extends ActionSupport{
	
	public static final String Character_Encoding = "UTF-8";
	
	public static final String TEXT_PLAIN = "text/plain";
	public static final String TEXT_HTML = "text/html";
	public static final String TEXT_XML = "text/xml";
	public static final String APPLICATION_JSON = "application/json";
	public static final String APPLICATION_XML = "application/xml";
	
	/**
	 * request.getParameter
	 * @param name
	 * @return
	 */
	public String getParameter(String name){
		HttpServletRequest request = ServletActionContext.getRequest();
		return request.getParameter(name);
	}
	
	/**
	 * request.getParameterValues
	 * @param name
	 * @return
	 */
	public String[] getParameters(String name){
		HttpServletRequest request = ServletActionContext.getRequest();
		return request.getParameterValues(name);
	}
	/**
	 * 从session里获取值
	 * @param name
	 * @return
	 */
	public String getSessionValue(String  name){
		return 	(String) ActionContext.getContext().getSession().get(name);
	}
	
	/**
	 * 写出类型为text/html的流
	 * @param str
	 * @param contentType
	 */
	public void write(String str, String contentType){
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter pw = null;
		try {
			response.setCharacterEncoding(Character_Encoding);
			response.setContentType(contentType);
			pw = response.getWriter();
			pw.write(str);
			pw.flush();
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 返回text/html数据
	 * @param str
	 */
	public void write(String str){
		this.write(str, TEXT_HTML);
	}
	
	/**
	 * 返回text/html数据
	 * @param str
	 */
	public void writeTextPlain(String str){
		this.write(str, TEXT_PLAIN);
	}
	
	/**
	 * 返回JSON数据
	 * @param str
	 */
	public void writeJSON(String str) {
		this.write(str, APPLICATION_JSON);
	}
	
	/**
	 * 返回XML数据
	 * @param str
	 */
	public void writeXML(String str) {
		this.write(str, APPLICATION_XML);
	}
	 
}
